package ru.amse.vlassiev.view;

import javax.swing.*;
import javax.swing.tree.*;

import ru.amse.vlassiev.model.IFiltrator;

import java.awt.event.*;


public class FilterTree extends JPanel
{
    private JTree myTree;
    private IFiltrator myFiltrator;
    
    public FilterTree(IFiltrator filtrator)
    {
    	super();
        this.addMouseListener(new MouseAdapter() {
        	public void mouseClicked(MouseEvent e) {
        		if (e.getClickCount() == 2) {
                   	if (JOptionPane.showConfirmDialog(null, "Do you want to create new item?") == JOptionPane.YES_OPTION) {
                   		addNewItem();
                   	} else if (JOptionPane.showConfirmDialog(null, "Do you want to delete this item?") == JOptionPane.NO_OPTION) {
                   		removeItem();
                   	}
        		}
        }
        });
        myTree = new JTree(new DefaultMutableTreeNode("View"));
        myFiltrator = filtrator;
        this.add(myTree);
    }

    public void addNewItem()
    {
        DefaultTreeModel model = (DefaultTreeModel)myTree.getModel();
        Object o = myTree.getLastSelectedPathComponent();
        if(o != null)
        {
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) o;
           	String name = JOptionPane.showInputDialog("Please input view's name.");
           	String type = JOptionPane.showInputDialog("Please input view's type (\"table\", \"graph\").");
           	myFiltrator.addView(new Graph("test|test|test"));
            DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(name);
            model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
            myTree.expandPath(new TreePath(selectedNode.getPath()));
        }
    }

    public void removeItem()
    {
        DefaultTreeModel model = (DefaultTreeModel) myTree.getModel();
        Object o = myTree.getLastSelectedPathComponent();
        if(o!=null)
        {
            DefaultMutableTreeNode selectedItem = (DefaultMutableTreeNode) o;
            if(!selectedItem.isRoot())
            {
                if(selectedItem.getChildCount() == 0)
                    model.removeNodeFromParent(selectedItem);
                else
                    JOptionPane.showMessageDialog(null, "Remove all subnodes first.");
            }
        }
    }

}